{include file="Public:header2"/}
<body style="min-height: 100%;background-color: #fff">
<div style="padding: 0 20px;position: relative;z-index: 99;border-bottom: 1px solid #e5e5e5;line-height: 39px;height: 39px;overflow: hidden;">
      <span style="visibility: visible;">
        <a href="{:url('/admin/seckill_product')}" style="padding-right: 8px;line-height: 22px;font-size: 14px;color: #333!important;">秒杀商城<span class="layui-box">&gt;</span></a>
        <a href="javascript:;"> <cite>编辑商品</cite></a>
      </span>
</div>
<link rel="stylesheet" href="/static/admin/style/font-awesome.min.css" media="all">
<style>
    .detail_image_son{display: inline-block;position: relative;margin-right: 10px;}
    .detail_image_son i{position: absolute;top: -12px;right: -7px;cursor: pointer;}
    .detail_image_son img{width:165px;height: 158px}
    .layui-btn-zdy{margin-bottom: 5px;background-color: #fff;color: #555;border: 1px solid #C9C9C9;}
    .spec-input{width: 134px;height: 30px;border-radius: 3px}
    .spec-item-input{width: 184px;display: inline-block;height: 30px;border-radius: 3px}
    #spec-item-add,#spec-item-del{display: inline-block;padding: 0 10px;height: 30px;line-height: 30px;}
    .layui-btn-zdy:hover {color: #555;border: 1px solid #009688b8}
    #spec-add,#spec-del{font-size: 10px;padding: 0 12px}
    #refresh-spec-price{height: 28px;line-height: 28px;margin-top: 10px;color: orangered;border: 1px solid orangered}
    .spec-price-input{width: 70px;display: inline-block;border-radius: 3px;margin-right: 2px}
    .tongbu-price{display: inline;cursor: pointer}
    .layui-btn-zdy-s{height: 28px;line-height: 28px;padding: 0 5px;display: inline-block}
</style>

<div class="layui-fluid">
    <div class="layui-row layui-col-space15">
        <div class="layui-col-md12">
            <div class="layui-card">
                <div class="layui-card-body">
                    <form onsubmit="return false;" id="form-data">
                        <div class="layui-form" wid100 lay-filter="">
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品名称</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="title" value="{$info.title}" style="width: 900px;" placeholder="请输入商品名称" autocomplete="off" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">分类</label>
                                <div class="layui-input-inline cate1">
                                    <select name="cate_id1" lay-verify="" lay-filter="choose">
                                        <option value="0">--请选择一级分类--</option>
                                        {foreach name="cate" item="vo"}
                                        <option {if condition="$info['cate_id1'] eq $vo['id']"} selected {/if} value="{$vo.id}">{$vo.title}</option>
                                        {/foreach}
                                    </select>
                                </div>
                                <div class="layui-input-inline cate2">
                                    <select name="cate_id2" lay-verify="">
                                        {foreach name="cate2" item="voo"}
                                        <option {if condition="$info['cate_id2'] eq $voo['id']"} selected {/if} value="{$voo.id}">{$voo.title}</option>
                                        {/foreach}
                                    </select>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品状态</label>
                                <div class="layui-input-inline" style="width: 900px">
                                    <input type="radio" name="status" value="0" title="上架"  {if $info.status eq 0} checked {/if}>
                                    <input type="radio" name="status" value="1" title="下架"  {if $info.status eq 1} checked {/if}>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品主图</label>
                                <div class="layui-input-inline">
                                    <button class="layui-btn layui-btn-zdy"  id="imgurl" >上传图片</button>
                                    <div class="layui-progress" id="progress_imgurl" lay-filter="progress_imgurl" lay-showPercent="true" style="display: none;margin-bottom:10px">
                                        <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
                                    </div>
                                    <input type="hidden" name="image" value="{$info.image}" lay-verify="required" placeholder="请上传图片" autocomplete="off" class="layui-input" >
                                    <img style="float:left;width:111px;height: 111px" id="image"  src="{:imageUrl($info.image)}">
                                </div>
                            </div>

                            <div class="layui-form-item">
                                <label class="layui-form-label">商品图片</label>
                                <div class="layui-input-inline" style="width: 80%">
                                    <button class="layui-btn layui-btn-zdy"  id="detail_image" >上传图片</button>
                                    <div  class="layui-progress" id="progress_imgurl_detail" lay-filter="progress_imgurl_detail" lay-showPercent="true" style="display: none;margin-bottom:10px;width: 150px">
                                        <div class="layui-progress-bar layui-bg-red" lay-percent="0%"></div>
                                    </div>
                                    <div class="detail_image_par">
                                        {foreach $detail_image_arr as $k => $v}
                                        <div class="detail_image_son">
                                            <img   src="{:imageUrl($v)}"><i onclick="$(this).parent().remove();detail_image_del({$k})" class="layui-icon layui-icon-close-fill" style="right: -2px;"></i>
                                        </div>
                                        {/foreach}
                                    </div>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品排序</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="sort"  style="width: 900px;"  value="{$info.sort}" maxlength="6"  placeholder="请输入商品排序" onkeyup = "value=value.replace(/[^\d]/g,'')" class="layui-input">
                                    <span style="color: #555555a6">数字越大排序越靠前</span>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品销量</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="sale_num"  style="width: 900px;"  value="{$info.sale_num}" maxlength="9"  placeholder="请输入商品销量" onkeyup = "value=value.replace(/[^\d]/g,'')" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">商品运费</label>
                                <div class="layui-input-inline">
                                    <input type="text" name="freight" value="{$info.freight}"  style="width: 900px;" maxlength="9"  placeholder="请输入商品运费" class="layui-input">
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <label class="layui-form-label">设置规格</label>
                                <div class="layui-input-inline" style="width: 80%">
                                    <!-- 规格项-->
                                    <table class="layui-table spec-table" style=" width: 900px" >
                                        <thead>
                                        <tr>
                                            <th>规格类型</th>
                                            <th>规格名称</th>
                                            <th style="width: 60px;">操作</th>
                                        </tr>
                                        </thead>
                                        <tbody class="spec-tbody">
                                        {foreach $guigedata as $key => $vo}
                                        <tr>
                                            <td>
                                                <input  type="text" name="spec_name"  value="{$vo['title']}" class="layui-input spec-input">
                                            </td>
                                            <td>
                                                <div class="spec-item-par">
                                                    {foreach $vo.items as $k => $v}
                                                    <div class="spec-item-son">
                                                        <input type="text" value="{$v['title']}" class="layui-input  spec-item-input">
                                                        {if $k eq 0}
                                                        <button class="layui-btn layui-btn-zdy" id="spec-item-add" onclick="spec_item_add($(this))">
                                                            <i class="fa fa-plus"></i>
                                                        </button>
                                                        {else/}
                                                        <button class="layui-btn layui-btn-zdy" id="spec-item-del" onclick="$(this).parent().remove();">
                                                            <i class="fa fa-remove"></i>
                                                        </button>
                                                        {/if}
                                                    </div>
                                                    {/foreach}
                                                </div>
                                            </td>
                                            <td>
                                                {if $key eq 0}
                                                <button class="layui-btn layui-btn-zdy" id="spec-add">添加</button>
                                                {else/}
                                                <button class="layui-btn layui-btn-zdy"  id="spec-del"  onclick="$(this).parent().parent().remove();">删除</button>
                                                {/if}
                                            </td>
                                        </tr>
                                        {/foreach}
                                        </tbody>
                                    </table>
                                    <!-- 刷新-->
                                    <button class="layui-btn layui-btn-zdy" id="refresh-spec-price" onclick="refreshPrice()">
                                        <i class="fa fa-refresh"></i>刷新价格表
                                    </button>
                                    <!-- 刷新价格-->
                                    <table class="layui-table spec-price-table" style="width: 900px !important;" >

                                    </table>
                                </div>
                            </div>
                            <div class="layui-form-item layui-form-text">
                                <label class="layui-form-label">商品详情</label>
                                <div class="layui-input-block">
                                    <script type="text/plain" name="content" id="editor" style="height:400px;width: 900px">{$info.content|raw}</script>
                                </div>
                            </div>
                            <div class="layui-form-item">
                                <input type="file"  id="spec_price_pic" accept="image/*" style="display: none" onchange="spec_price_pic_image(event)">

                                <div class="layui-input-block">
                                    <input type="hidden" value="{$info.id}" name="id">
                                    <button class="layui-btn" onclick="return check()">确认保存</button>
                                </div>
                            </div>
                        </div>
                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
{include file="Public:footer"/}
</body>
</html>
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/ueditor.config.js"></script>
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/ueditor.all.min.js"> </script>
<script type="text/javascript" src="/static/admin/lib/ueditor/1.4.3/lang/zh-cn/zh-cn.js"></script>
<script type="text/javascript" src="/static/admin/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    var preoss = "{:imageUrl('0')}"

    var detail_image_arr = {:json_encode($detail_image_arr)};

    var filename = [];
    var specs = [];
    var oldgglist = {:json_encode($newgglist)};

    layui.use(['layer','form','upload','element','laydate'], function(){
        var $ = layui.$;
        var form = layui.form;
        var laydate = layui.laydate;
        var upload = layui.upload;
        var element = layui.element; 

        //富文本
        $(function(){
            var ue = UE.getEditor('editor');
            refreshPrice();
        })

        //主图
        var uploadInst = upload.render({
            accept:'imgurl'
            ,elem: '#imgurl' //绑定元素
            ,url: '/admin/picture' //上传接口
            ,progress: function(n, elem){
                $("#progress_imgurl").show();
                var percent = n + '%' //获取进度百分比
                element.progress('progress_imgurl', percent); //可配合 layui 进度条元素使用
            }
            ,done: function(res){
                //上传完毕回调
                if(res.status == 1){ //成功
                    layer.msg("上传成功",{icon:1,time:1000},function(){
                        $("#image").attr("src",res.data.path);  //单图
                        $("input[name=image]").val(res.data.imgurl);
                        element.progress('progress_imgurl', '0%');
                        $("#progress_imgurl").css('display','none');
                    });
                }else{ //失败
                    layer.msg(res.msg,{icon:2,anim:6,time:1500});
                }
            }
            ,error: function(){
                //请求异常回调
                layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
            }
        });
        //多图
        var uploadInstDetail = upload.render({
            accept:'imgurl'
            ,elem: '#detail_image' //绑定元素
            ,url: '/admin/picture' //上传接口
            ,progress: function(n, elem){

                $("#progress_imgurl_detail").show();
                var percent = n + '%' //获取进度百分比
                element.progress('progress_imgurl_detail', percent); //可配合 layui 进度条元素使用
            }
            ,done: function(res){

                //上传完毕回调
                if(res.status == 1){ //成功
                    layer.msg("上传成功",{icon:1,time:1000},function(){
                        detail_image_arr.push(res.data.imgurl)
                        var index =  detail_image_arr.length-1;
                        var html = '';
                        html+='<div class="detail_image_son">';
                        html+='<img  src="'+res.data.path+'">';
                        html+='<i onclick="$(this).parent().remove();detail_image_del('+index+')" class="layui-icon layui-icon-close-fill"></i>';
                        html+='</div>';
                        $(".detail_image_par").append(html);
                        element.progress('progress_imgurl_detail', '0%');
                        $("#progress_imgurl_detail").css('display','none');
                    });
                }else{ //失败
                    layer.msg(res.msg,{icon:2,anim:6,time:1500});
                }
            }
            ,error: function(){
                //请求异常回调
                layer.msg('服务繁忙，请稍后再试',{icon:2,anim:6,time:1500});
            }
        });

        //添加大规格
        $("#spec-add").click(function () {
            var str = '';
            str += '<tr><td><input  type="text" name="spec_name" autocomplete="off" value="" placeholder="请输入规格类型" class="layui-input spec-input"></td>';
            str += '<td><div class="spec-item-par"><div class="spec-item-son">';
            str += '<input type="text" value=""  autocomplete="off" placeholder="请输入规格名称" class="layui-input  spec-item-input">';
            str += '  <button class="layui-btn layui-btn-zdy" id="spec-item-add"  onclick="spec_item_add($(this))"><i class="fa fa-plus"></i></button></div></div> </td>';
            str += '<td><button class="layui-btn layui-btn-zdy"  id="spec-del"  onclick="$(this).parent().parent().remove();">删除</button></td></tr>';
            $(".spec-tbody").append(str);
        })
        //获取二级分类
        form.on('select(choose)', function(data) {
            // console.log(data.elem); //得到select原始DOM对象
            // console.log(data.value); //得到被选中的值
            var url = "{:url('/admin/producttwocate')}";
            var cate_id  = data.value;

            if(cate_id == 0) {
                $(".cate2").remove();
                return ;
            }
            $.post(url,{"cate_id":cate_id},function(da){
                $(".cate2").remove();
                $(".cate1").after(da);
                form.render('select');//select是固定写法 不是选择器
            })
        });



    });
    //删除多图
    function detail_image_del(index) {
        delete detail_image_arr[index]
    }
    //添加小规格
    function spec_item_add(obj) {
        var str = '';
        str += '<div class="spec-item-son">';
        str += '<input type="text" autocomplete="off" placeholder="请输入规格名称"  class="layui-input  spec-item-input">';
        str += '  <button class="layui-btn layui-btn-zdy" id="spec-item-del" onclick="$(this).parent().remove();">';
        str += '<i class="fa fa-remove"></i></button>';
        str += '</div>';
        obj.parent().parent().append(str)
    }



    //获取价格
    function refreshPrice() {
        var kongval = 0
        $(".spec-table").find("input").each(function () {
            if ($(this).val() == '') kongval = 1
        })
        if (kongval) {
            layer.msg('不能有空值', {icon: 2, time: 1000});
            return;
        }
        specs = [];//规格集合
        var i = 0;
        $('input[name=spec_name]').each(function () {
            specs_items = [];//规格小类集合
            var j = 0;
            $(this).parent().next().find('input').each(function () {
                specs_items.push({'k': j, 'title': $(this).val()});
                j++
            })
            specs.push({'k': i, 'title': $(this).val(), 'items': specs_items});
            i++;
        });

        var len = specs.length;
        var newlen = 1;
        var h = new Array(len);
        var rowspans = new Array(len);

        var html = '<thead><tr>';
        for(var i=0;i<len;i++){
            html+="<th>" + specs[i].title + "</th>";
            var itemlen = specs[i].items.length;
            if(itemlen<=0) { itemlen = 1 };
            newlen*=itemlen;
            h[i] = new Array(newlen);
            for(var j=0;j<newlen;j++){
                h[i][j] = new Array();
            }
            var l = specs[i].items.length;
            rowspans[i] = 1;
            for(j=i+1;j<len;j++){
                rowspans[i]*= specs[j].items.length;
            }
        }

        html += '<th>售价（元）</th>';
        html += '<th>原价（元）</th>';
        html += '<th>库存</th>';
        html += '<th style="width: 120px">图片</th>';
        html += '</tr></thead>';


        for(var m=0;m<len;m++){
            var k = 0,kid = 0,n=0;
            for(var j=0;j<newlen;j++){
                var rowspan = rowspans[m];
                if( j % rowspan==0){
                    h[m][j]={ k:specs[m].items[kid].k,title: specs[m].items[kid].title, html: "<td rowspan='" +rowspan + "'>"+ specs[m].items[kid].title+"</td>\r\n",id: specs[m].items[kid].id};
                }else{
                    h[m][j]={ k:specs[m].items[kid].k,title:specs[m].items[kid].title, html: "",id: specs[m].items[kid].id};
                }
                n++;
                if(n==rowspan){
                    kid++; if(kid>specs[m].items.length-1) { kid=0; }
                    n=0;
                }
            }
        }

        var hh = "";
        for(var i=0;i<newlen;i++) {
            hh += "<tr>";
            var ks = [];
            var titles = [];
            for (var j = 0; j < len; j++) {
                hh += h[j][i].html;
                ks.push(h[j][i].k);
                titles.push(h[j][i].title);
            }
            ks2 = ks.join('_');
            ks = ks.join(',');
            titles = titles.join(',');


            if (typeof (oldgglist[ks]) != 'undefined') {
                var val = oldgglist[ks];
            } else {
                var val = {
                    price: '',
                    seckill_price: 0,
                    deposit_price: 0,
                    integral_price: 0,
                    stock: '1000',
                    pic: '',
                };
            }


            hh += '<td>';
            hh += '	<input name="option['+ks+'][name]" type="hidden" value="'+titles+'" class="layui-input"/><input name="option['+ks+'][price]" type="text"  autocomplete="off"   value="'+(val.price==null?'':val.price)+'" class="layui-input spec-price-input"/>';
            if(i==0){
                hh += ' <i class="fa fa-hand-o-down tongbu-price"  title="批量设置" onclick="plset(\'price\')" ></i>';
            }else{
                hh += ' <i style="visibility: hidden" class="fa fa-hand-o-down tongbu-price"  title="批量设置" ></i>';
            }
            hh += '</td>';
            hh += '<td>';
            hh += ' <input name="option['+ks+'][seckill_price]" type="text"  autocomplete="off"   value="'+(val.seckill_price==null?'':val.seckill_price)+'" class="layui-input spec-price-input"/>';
            if(i==0){
                hh += ' <i class="fa fa-hand-o-down tongbu-price"  title="批量设置" onclick="plset(\'seckill_price\')"></i>';
            }else{
                hh += ' <i style="visibility: hidden" class="fa fa-hand-o-down tongbu-price"  title="批量设置" ></i>';
            }
            hh += '</td>';
            hh += '<td>';
            hh += ' <input name="option['+ks+'][stock]" type="text"  autocomplete="off"   value="'+(val.stock==null?'':val.stock)+'" class="layui-input spec-price-input"/>';
            if(i==0){
                hh += ' <i class="fa fa-hand-o-down tongbu-price"  title="批量设置" onclick="plset(\'stock\')"></i>';
            }else{
                hh += ' <i style="visibility: hidden" class="fa fa-hand-o-down tongbu-price"  title="批量设置" ></i>';
            }
            hh += '</td>';
            hh += '<td id="ggpic'+ks2+'">' +
                '<input type="hidden" name="option['+ks+'][pic]" id="ggpicval'+ks2+'" value="'+(val.pic==null?'':val.pic)+'"/>';
                if(val.pic)   {
            hh +='<img class="thumb_img" src="'+preoss+val.pic+'" style="width:50px; height: 50px;"/> ';
                }else{
            hh +='<img class="thumb_img" src="" style="width:50px; height: 50px;display: none"/> ';
                }
            hh +='<label class="layui-btn layui-btn-sm layui-btn-primary layui-btn-zdy-s" onclick="openBrowse(this);">上传</label>' +
                '</td>';
            hh += "</tr>";
        }
        html+=hh;
        $(".spec-price-table").html(html);

    }

    //批量设置价格
    function plset(name){
        $("input[name$='["+name+"]']").val($("input[name$='["+name+"]']").eq(0).val());
    }

    function openBrowse(obj){
        var ie=navigator.appName=="Microsoft Internet Explorer" ? true : false;
        if(ie){
            document.getElementById("file").click();
        }else{
            var a=document.createEvent("MouseEvents");//FF的处理
            a.initEvent("click", true, true);
            document.getElementById("spec_price_pic").dispatchEvent(a);
        }
        filename = $(obj);
    }

    //上传图片
    function spec_price_pic_image(e) {
        var $ = layui.$;
        var file = document.querySelector("#spec_price_pic").files[0];
        if(!file){
            return;
        }
        var formdata = new FormData();
        formdata.append("file",file);
        $.ajax({
            url: "{:url('/admin/picture')}",
            type: 'post',
            data: formdata,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function (res) {
                $("#spec_price_pic").val('');
                if (res.status == 1){
                    filename.prev().attr('src',res.data.path)
                    filename.prev().show();
                    filename.prev().prev().val(res.data.imgurl)
                }else{
                    layer.msg('上传失败',{icon:2,time:1000});
                }
            },
            error: function (error) {
                layer.msg('系统错误!!!',{icon:2,time:1000});
            }
        })
    }

    function check(){
        var $ = layui.$;
        var load=layer.load(2);
        var data = new FormData(document.getElementById('form-data'));
        data.append('spec_data', JSON.stringify(specs))
        data.append('detail_image', JSON.stringify(detail_image_arr))
        $.ajax({
            url: "{:url('/admin/seckill_product_edit')}",
            type: 'post',
            data: data,
            dataType: 'json',
            processData: false,
            contentType: false,
            success: function (data) {
                if (data.status == 1) {
                    layer.msg(data.msg, {icon: 1, time: 1000}, function () {
                        location.href = "{:url('/admin/seckill_product')}";
                    });
                } else {
                    layer.msg(data.msg, {icon: 2, anim: 6, time: 1500}, function () {
                        layer.close(load);
                    });
                }
            },
            error: function (error) {
                layer.close(load);
            },
        })

    }
</script>
